package com.hl.toolkit.server.util;

/**作者：吴润
链接：https://zhuanlan.zhihu.com/p/25463973
来源：知乎
著作权归作者所有，转载请联系作者获得授权。*/

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

/**
 * @author RunDouble
 * 
 */
public class PictureInZhihu{
	private static final String webUrl="http://lab.grapeot.me/zhihu/autoface";
	
	private static  int num=0;

	
		public   static  HashMap<String, String> getUsersUrlAndprofileUrl() {
		Document document;
		String addressLinkHref;
		String profileLinkSrc = "";
		HashMap<String, String> urlWithProfile = new HashMap<>();
		try {
			document = Jsoup.connect(webUrl).get();
			Elements links = document.select("a[href]");
			for (int i = 0; i < links.size(); i++) {
				addressLinkHref = links.get(i).attr("href");
				try {
					document = Jsoup.connect(addressLinkHref).get();

				} catch (Exception e) {
					i++;
					continue;
				}
				Elements jpgs = document.select("img[src$=.jpg]");
				if (jpgs.size() != 0) {
					profileLinkSrc = jpgs.get(0).attr("src");
				}
				System.out.println(addressLinkHref);
				System.out.println(profileLinkSrc + "\n\n");
 	 
				 picturePersistence(profileLinkSrc);
			}

		} catch (Exception e) {
			e.printStackTrace();

		}
		return urlWithProfile;
	}
/**
 * 全部写入
 * */
	public static  void picturePersistence (String urlWithProfile) {
 	   
  	    			try {
 	   				URL url = new URL(urlWithProfile);
 	   				HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
 	   				httpURLConnection.setReadTimeout(50000);
 	   				InputStream inputStream = httpURLConnection.getInputStream();
 	   				
 	   				String newImageName = String.valueOf(System.currentTimeMillis()) +num+".jpg";
 	   				File file = new File("zhihupics");
 	   				if (!file.exists()) {
 	   					file.mkdir();
 	   				}

 	   				FileOutputStream fos = new FileOutputStream("D:\\"+file.getPath()+ "\\" + newImageName);
 	   				System.out.println(file.getPath()+ "/" + newImageName);

 	   				byte[] buffer = new byte[1024];
 	   				int length;
 	   				while ((length = inputStream.read(buffer)) > 0) {
 	   					fos.write(buffer, 0, length);
 	   				}
 	   			inputStream.close();  
 	   	        fos.flush();  
 	   	        fos.close();  
 	   				num++;
 	    			} catch (Exception e) {
 	    				e.printStackTrace();
 	    			}
 	   		 
   		  
 	
 	}

 
	
	
 
	/*
	 * just a test
	 */
	public static void main(String[] args) {
		double start = System.currentTimeMillis();

 		PictureInZhihu.getUsersUrlAndprofileUrl();
  		
		double end = System.currentTimeMillis();
		double totalTime = ((end - start) / 1000) / 60;
		System.out.println("Total time:" + totalTime + "miniutes.");
	}

	 
}
